import Router from 'koa-router';
import { validationMiddleware } from '../../middleware/validationMiddleware';
import { AdminRegisterDto } from './AdminRegister.dto';
import {
  adminEmailVerify,
  adminLoginService,
  AdminPasswordUpdateService, AdminRegisterService,
  AdminTokenCheck
} from '../../service/AdminService';
import { routes } from '../../routes';
import Result from '../../vo/result';
import { ResultCode, ResultCodeMessages } from '../../enums/resultCode';
import path from 'node:path';
import * as fs from 'fs';
import koaBody from 'koa-body';
import logger from '../../Logger/logger';
import { extractTokenFromHeader } from '../../utits/utits';
import { AdminLoginDto } from './AdminLogin.dto';

require('dotenv').config();

const router = new Router({
  prefix: '/api'
});
const isProduction = process.env.NODE_ENV === 'production';

const uploadDir = path.join(__dirname, isProduction ? './assets' : '../../../assets');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}


router.post(routes.ADMIN_LOGIN, validationMiddleware(AdminLoginDto), async ctx => {
  const body: any = ctx.request.body;
  return ctx.body = await adminLoginService(body.username, body.password);
});

router.post(routes.ADMIN_PASSWORD_UPDATE, validationMiddleware(AdminRegisterDto), async ctx => {
  return ctx.body = await AdminPasswordUpdateService(ctx);
});

router.get(routes.ADMIN_TOKEN_CHECK, async ctx => {
  const token = extractTokenFromHeader(ctx);
  if (!token) {
    return ctx.body = Result.fail(ResultCode.MISSING_TOKEN, ResultCodeMessages[ResultCode.MISSING_TOKEN]);
  }
  return ctx.body = await AdminTokenCheck(token);
});

router.post(routes.ADMIN_UPLOAD, koaBody({
  multipart: true
}), async (ctx: any) => {
  const { file } = ctx.request?.files;
  if (!file) {
    return ctx.body = Result.fail(ResultCode.FAIL, '文件上传失败，请检查文件是否存在');
  }
  const regType = /\.(png|jpg|jpeg)$/;
  const regMimeType = /image\/(png|jpg|jpeg)$/;
  if (!regMimeType.test(file.mimetype) || !regType.test(file.originalFilename)) {
    return ctx.body = Result.fail(ResultCode.FAIL, '文件类型错误');
  }
  if (file.size > 2 * 1024 * 1024) return ctx.body = Result.fail(ResultCode.FAIL, '文件大小不得超过2M');
  const newFilename = file.newFilename + '.' + file.mimetype.split('/')[1];
  const safePath = path.resolve(uploadDir, newFilename);
  if (!safePath.startsWith(uploadDir)) {
    return ctx.body = Result.fail(ResultCode.FAIL, '非法文件路径');
  }
  fs.copyFileSync(file.filepath, path.resolve(uploadDir, safePath));
  return ctx.body = Result.success({
    url: 'http://127.0.0.1:3000/assets' + '/' + newFilename,
    fileName: newFilename
  }, '文件上传成功');
});

router.post(routes.ADMIN_DELETE_ASSET, async ctx => {
  const { fileName } = ctx.request.body;
  console.log(fileName)
  const filePath = path.resolve(uploadDir, fileName);
  if (!fs.existsSync(filePath)) {
    return ctx.body = Result.fail(ResultCode.FAIL, '文件不存在');
  }
  fs.unlinkSync(filePath);
  return ctx.body = Result.success(null, '文件删除成功');
});

router.post(routes.ADMIN_REGISTER, validationMiddleware(AdminRegisterDto), async ctx => {
  const { username, password, email, code } = ctx.request.body;
  return ctx.body = await AdminRegisterService(username, password, email, code);
});

router.post(routes.ADMIN_REGISTER_VERIFY, async ctx => {
  const { email } = ctx.request.body;
  return ctx.body = await adminEmailVerify(email);
});


export default router.routes();